import configparser
import os
import webview
import threading
import time
import keyboard

from src.Muport import Muport

configs = configparser.ConfigParser()
fileName = "config.ini"
if os.path.exists(fileName):
    configs.read(fileName)
else:
    default_config = {
        "DEFAULT":{
            "visible_fast":"F12",#隐藏/显示窗口热键
            "title":"PyWebView + 本地 HTTP 服务",#窗口标题
            "width":"800",#窗口宽度
            "height":"600",#窗口高度
            "x":"null",#窗口x坐标
            "y":"null",#窗口y坐标
            "debug":"false",#是否开启调试模式
            "resizable":"true",#是否可缩放
            "fullscreen":"false",#是否全屏
            "min_size":"200,100",#窗口最小尺寸
            "hidden":"false",#是否隐藏窗口
            "frameless":"false",#是否无边框
            "shadow":"false",#是否有阴影
            "focus":"true",#是否聚焦
            "on_top":"false",#是否置顶
            "confirm_close":"false",#是否显示关闭窗口提示
            "background_color":"#FFFFFF",#背景颜色
        }
    }
    configs.read_dict(default_config)
    with open(fileName, "w") as f:
        configs.write(f)
if 'port' in configs['DEFAULT']:
    PORT = int(configs['DEFAULT']['port'])
else:
    PORT = None
PORT = Muport().get_port(PORT)
http_server = None # HTTP 服务器对象
WINDOW = None # pywebview 窗口对象
running = True # 程序运行状态
WINDOW_STATUS = True
print(configs.get("DEFAULT","debug"))
newFileName = "log.log"
line = f"{PORT}\n"
# fw = open(newFileName, '', encoding='utf-8')
if os.path.exists(newFileName):
    with open(newFileName, 'a', encoding='utf-8') as f:
        f.write(line)
else:
    with open(newFileName, 'a', encoding='utf-8') as f:
        f.write(line)
# 启动键盘监听
def start_keyboard_listener(key,cllback):
    # 监听 F12 键（keyboard 库直接支持）
    print(f"监听{key}")
    keyboard.add_hotkey(key,cllback)
    # 保持监听
    # keyboard.wait()  # 阻塞线程，一直监听
    while running:
        time.sleep(0.1)
    keyboard.unhook_all()
# 隐藏/显示窗口
def visible_fast():
    # print("按下F12")
    global WINDOW
    global WINDOW_STATUS
    print(WINDOW_STATUS)
    if WINDOW_STATUS:
        WINDOW.hide()
        WINDOW_STATUS = False
    else:
        WINDOW.show()
        WINDOW_STATUS = True
# 创建 JSAPI
class JSAPI:
    def visible(self):
        print("切换全屏")
        # WINDOW.toggle_fullscreen()
    def start(self):
        print("开始")
# print("端口：", PORT)
if __name__ == '__main__':
    # 创建隐藏显示窗口
    if configs['DEFAULT']['visible_fast']:
        # start_keyboard_listener(configs['DEFAULT']['visible_fast'],visible_fast)
        listener_thread = threading.Thread(target=start_keyboard_listener, args=(configs['DEFAULT']['visible_fast'],visible_fast))
        listener_thread.start()




    # 创建 pywebview 窗口，加载本地服务首页
    WINDOW = webview.create_window(
        title=configs['DEFAULT']['title'],
        url="index.html",  # 加载 http://localhost:8000/index.html
        js_api=JSAPI(),
        width=configs.getint("DEFAULT","width"),
        height=configs.getint("DEFAULT","height"),
        resizable=configs.getboolean("DEFAULT","resizable"),
        fullscreen=configs.getboolean("DEFAULT","fullscreen"),
        min_size=(int(configs['DEFAULT']['min_size'].split(",")[0]),int(configs['DEFAULT']['min_size'].split(",")[1])),
        hidden=configs.getboolean("DEFAULT","hidden"),
        frameless=configs.getboolean("DEFAULT","frameless"),
        shadow=configs.getboolean("DEFAULT","shadow"),
        focus=configs.getboolean("DEFAULT","focus"),
        on_top=configs.getboolean("DEFAULT","on_top"),
        background_color=configs['DEFAULT']['background_color']
    )
    # 启动 GUI
    webview.start(
        debug=configs.getboolean("DEFAULT","debug"),
        http_server=True,

    )
    running = False
    # 等待键盘监听线程结束
    if configs['DEFAULT']['visible_fast']:
        listener_thread.join()
    print("结束程序")